package org.afk.sisy.io;

import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;

import org.afk.sisy.*;
import org.afk.tools.log.*;

public class DeleteAllVisitor implements FileVisitor<Path>
{
	private final ErrorHandler errorHandler;
	private final SisyProgress progress;

	public DeleteAllVisitor(final SisyProgress progress, final ErrorHandler errorHandler)
	{
		this.progress = progress;
		this.errorHandler = errorHandler;
	}

	@Override
	public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException
	{
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException
	{
		try
		{
			Files.delete(file);
			errorHandler.info("Deleted " + file);
			progress.incDeleted(1);
		}
		catch (final NoSuchFileException e)
		{}
		catch (final Exception e)
		{
			errorHandler.warning("while deleting file " + file, e);
		}
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException
	{
		errorHandler.warning("while deleting " + file, exc);
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException
	{
		try
		{
			Files.delete(dir);
			errorHandler.info("Deleted folder " + dir);
			progress.incDeleted(1);
		}
		catch (final DirectoryNotEmptyException e)
		{}
		catch (final Exception e)
		{
			errorHandler.warning("while deleting folder " + dir, e);
		}
		return FileVisitResult.CONTINUE;
	}

}
